package com.luo.ai.assistant.chat.memory;

import com.luo.ai.assistant.conv.model.Chat;
import com.luo.ai.assistant.util.JsonUtils;
import org.springframework.ai.chat.messages.*;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 聊天消息转换器
 *
 * @author luohq
 * @date 2025-02-13 13:36
 */
public class ChatMessageConvertor {

    public static Message toMessage(Chat chat) {
        Message message = null;
        MessageType messageType = MessageType.fromValue(chat.getCreatedBy());
        Map<String, Object> metadata = JsonUtils.fromJson(chat.getMetadata(), Map.class);
        switch (messageType) {
            case USER:
                message = UserMessage.builder().text(chat.getContent()).metadata(metadata).build();
                break;
            case SYSTEM:
                message = new SystemMessage(chat.getContent());
                break;
            case ASSISTANT:
                message = new AssistantMessage(chat.getContent(), metadata);
                break;
            case TOOL:
                //TODO 各种类型存储、转换待完善
                //message = new ToolMessage();
                //break;
            default:
                break;
        }
        return message;
    }

    public static Chat toChat(String conversationId, Message message) {
        Chat chat = new Chat();
        chat.setConversationId(Long.valueOf(conversationId));
        chat.setContent(message.getText());
        chat.setMetadata(JsonUtils.toJson(message.getMetadata()));
        chat.setCreateTime(LocalDateTime.now());
        chat.setCreatedBy(message.getMessageType().getValue());
        return chat;
    }
}
